const config = {
	handshakeCommand: 'hello.redduck.chat.',
	open(client) {
		console.log('OPEN')
	},
	data(client, data) {
		console.log('RECEIVED', data)
		if (data.type === 'error') {
			console.error(data.content)
			toast(data.content, 'error', 'Redduck Error')
		} else if (data.type === 'message') {
			addMessage(data.content)
		}
	},
}
let client = undefined
document.getElementById('connect').addEventListener('click', function () {
	if (client) {
		toast('RedDuck client is already running!', 'info')
	} else {
		let username = document.getElementById('username').value
		let serverId = document.getElementById('serverId').value
		if (username && serverId) {
			client = createRedDuckClient(config, serverId, username)
		} else {
			if (serverId)
				toast('username is empty!', 'error', 'Error')
			else
				toast('serverId is empty!', 'error', 'Error')
		}
	}
})
document.getElementById('close').addEventListener('click', function () {
	if (client) {
		client.close()
		client = undefined
	} else {
		toast('No RedDuck client is running!', 'info')
	}
})
document.getElementById('send').addEventListener('click', function () {
	if (client) {
		let messageText = document.getElementById('message').value
		document.getElementById('message').value = ''
		let message = { sender: client.username, date: new Date(), text: messageText }
		addMessage(message)

		client.send({ type: 'message', content: message })
	} else {
		toast('No RedDuck client is running!', 'info')
	}
})